package com.longge;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class FindRestaurant {

    public String[] findRestaurant(String[] list1, String[] list2) {
        HashMap<String, Integer> map1 = new HashMap<>();
        HashMap<String, Integer> map2 = new HashMap<>();
        for (int i = 0; i < list1.length; i++) {
            map1.put(list1[i], i);
        }
        for (int i = 0; i < list2.length; i++) {
            map2.put(list2[i], i);
        }
        int min = Integer.MAX_VALUE;
        ArrayList<String> ansList = new ArrayList<>();

        for (Map.Entry<String, Integer> entry : map1.entrySet()) {
            String key = entry.getKey();
            if (map2.get(key) != null) {
                int index = map2.get(key) + entry.getValue();
                if (index<min){
                    min = index;
                    ansList = new ArrayList<>();
                    ansList.add(key);
                }else if (index==min){
                    ansList.add(key);
                }
            }
        }
        return ansList.toArray(new String[0]);
    }

}
